package com.example.article.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.api.entity.article.Article;
import com.example.article.mapper.ArticleMapper;
import com.example.article.service.ArticleService;
import com.example.article.util.RedisClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author lr
 * @since 2023-02-18
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    private final ArticleMapper articleMapper;

    private final RedisClient redisClient;

    private static String BLOG_LIKED_KEY = "article:like:";

    @Override
    public Object insert(Article article) {
        article.setPraiseTotal(0);
        return articleMapper.insert(article);
    }

    @Override
    public Object likeBlog(String id, String userId) {
        final Article article = articleMapper.selectById(id);
        String key = BLOG_LIKED_KEY + article.getUserId() + ":" + id;
        Boolean isMember = redisClient.isMmeber(key, userId);
        if (BooleanUtil.isFalse(isMember)) {
            //3.如果未点赞，可以点赞
            //3.1 数据库点赞数+1
            article.setPraiseTotal(article.getPraiseTotal() + 1);
            final boolean isSuccess = article.updateById();
            //3.2 保存用户到Redis的set集合
            if (isSuccess) {
                redisClient.sadd(key, userId);
            }
        } else {
            //4.如果已点赞，取消点赞
            //4.1 数据库点赞数-1
            article.setPraiseTotal(article.getPraiseTotal() - 1);
            final boolean isSuccess = article.updateById();
            //4.2 把用户从Redis的set集合移除
            if (isSuccess) {
                redisClient.srem(key, userId);
            }
        }
        return null;
    }

    @Override
    public Object delete(int id) {
        return null;
    }

    @Override
    public Object update(Article article) {
        return null;
    }

    @Override
    public Article load(int id) {
        return null;
    }

    @Override
    public Map<String, Object> pageList(int offset, int pagesize) {
        return null;
    }
}
